package com.example.pool;

import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Slf4j
public class FTPClientPool {
    @Getter
    private GenericObjectPool<FTPClient> pool;
    private FTPClientFactory factory;

    public FTPClientPool(FTPClientFactory clientFactory) {
        this.factory = clientFactory;
        pool = new GenericObjectPool<>(clientFactory, clientFactory.getFtpPoolConfig());
    }

    public FTPClientFactory getClientFactory() {
        return factory;
    }

    /**
     * 借 获取一个连接对象
     *
     * @return
     * @throws Exception
     */
    public FTPClient borrowObject() throws Exception {
        FTPClient client = pool.borrowObject();
        if (!client.sendNoOp()) {
            client.logout();
            client.disconnect();
            pool.invalidateObject(client);
            client = factory.create();
            pool.addObject();
        }
        return client;

    }

    /**
     * 还 归还一个连接对象
     *
     * @param ftpClient
     */
    public void returnObject(FTPClient ftpClient) {

        if (ftpClient != null) {
            pool.returnObject(ftpClient);
        }
    }

}
